package com.meitianhui.convenitenbuy.module.order.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jakewharton.rxbinding.view.RxView;
import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseToolbarActivity;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.main.model.bean.UserToken;
import com.meitianhui.convenitenbuy.module.home.model.bean.OneOrder;
import com.meitianhui.convenitenbuy.module.mine.model.ConsumerAddress;
import com.meitianhui.convenitenbuy.module.mine.ui.activity.ReceivingAddressActivity;
import com.meitianhui.convenitenbuy.module.order.contract.OrderPayContract;
import com.meitianhui.convenitenbuy.module.order.di.DaggerOrderComponent;
import com.meitianhui.convenitenbuy.module.order.di.OrderModule;
import com.meitianhui.convenitenbuy.module.order.model.bean.UsableCash;
import com.meitianhui.convenitenbuy.module.order.presenter.OrderPayPresenter;
import com.meitianhui.convenitenbuy.module.wallet.model.PayResultBean;
import com.meitianhui.convenitenbuy.util.AddressUtil;
import com.meitianhui.convenitenbuy.util.RxBus;
import com.meitianhui.convenitenbuy.util.RxUtils;
import com.meitianhui.convenitenbuy.util.StringUtils;
import com.meitianhui.convenitenbuy.util.TipUtils;
import com.meitianhui.convenitenbuy.widget.dialog.PasswordDialog;

import java.util.List;

import javax.inject.Inject;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Created by Administrator on 2017/11/20.
 */

public class OrderPayActivity extends BaseToolbarActivity implements OrderPayContract.View, RadioGroup.OnCheckedChangeListener,PasswordDialog.OnDialogPsdCompleteListener {
    private RadioGroup mRgOrderPay;
    private int mPayWay = 0;//默认钱包支付
    private String mNum = "";
    private String mItemId = "";
    private OneOrder mOneType;
    private TextView mTvTitle, mTvContent, mTvNumber, mTvPrice, mTvPayMoney;
    private RelativeLayout mRlWallet,mRlAddress;
    private TextView mTvWallet;
    private TextView mTvNameAndTel,mTvAddress;
    private EditText mEtFeedBack;
    private RadioButton mRbWallet,mRbAlipay;
    private String mFromPage;
    private String mWalletMoney="0";
    private PasswordDialog mPasswordDialog;
    private List<ConsumerAddress.ConsumerData> consumerDataList;

    //支付需要传递的参数   品牌领中跳转过来的
    private String mDeliveryAddress = " ",mContactPerson = "", mContactTel = "";


    @Inject
    OrderPayPresenter presenter;

    @Override
    protected int setView() {
        return R.layout.activity_order_pay;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        DaggerOrderComponent.builder()
                .appComponent(App.getInstance().getAppComponent())
                .orderModule(new OrderModule(this))
                .build()
                .inject(this);
        initView();
        initData();
    }

    private void initView() {
        isEnable(false);
        setTbTitle("订单支付");
        mRgOrderPay = getViewById(R.id.rg_order_pay);
        mRgOrderPay.setOnCheckedChangeListener(this);
        mTvTitle = getViewById(R.id.tv_title);
        mTvContent = getViewById(R.id.tv_content);
        mTvWallet = getViewById(R.id.tv_wallet);
        mTvNumber = getViewById(R.id.tv_number);
        mTvPrice = getViewById(R.id.tv_price);
        mTvPayMoney = getViewById(R.id.tv_pay_money);
        mRlWallet = getViewById(R.id.rl_wallet);
        mRbAlipay = getViewById(R.id.rb_alipay);
        mRbWallet = getViewById(R.id.rb_wallet);
        mEtFeedBack = getViewById(R.id.et_feed_back);
        mTvNameAndTel = getViewById(R.id.tv_name_and_tel);
        mTvAddress = getViewById(R.id.tv_address);
        mRlAddress = getViewById(R.id.rl_address);
        RxUtils.bindEvents(mRlAddress,this);
        RxUtils.bindEvents(getViewById(R.id.btn_pay), this);
    }


    private void initData() {
        Intent intent = this.getIntent();
        mOneType = (OneOrder) intent.getSerializableExtra("order_info");
        mFromPage = intent.getStringExtra("from_page");
        if (mFromPage.equals(Constants.TYPE_GOLD_BUY)) {
            mTvTitle.setText(mOneType.title);
            mTvContent.setVisibility(View.GONE);
            mTvNumber.setText("1");
            mTvPrice.setText(mOneType.discount_price);
            mTvPayMoney.setText("¥" + mOneType.discount_price);
            mRlWallet.setVisibility(View.GONE);
            mRbWallet.setVisibility(View.GONE);
            RxView.visibility(getViewById(R.id.rl_feed_back)).call(true);
            RxView.visibility(mRlAddress).call(true);
            mRbAlipay.setChecked(true);
            mPayWay = 1;
        }else if(mFromPage.equals(Constants.TYPE_COUPON)){
            mNum = intent.getStringExtra("num");
            String title = intent.getStringExtra("title");
            String content = intent.getStringExtra("content");
            mItemId = intent.getStringExtra("item_id");
            String payMoney = intent.getStringExtra("pay_money");
            mTvTitle.setText(title);             //名称
            mTvContent.setText(content);         //
            mTvNumber.setText(mNum);
            mTvPrice.setText(payMoney);
            mTvPayMoney.setText("¥" + payMoney);
        }
        pushPayResult();
        presenter.getUsableCash();

    }

    @Override
    protected void onResume() {
        super.onResume();
        consumerDataList = InfoProvider.getUserReceivingAddress(this);
        if (consumerDataList != null) {
            if (consumerDataList.size() > 0) {
                for (int i= 0;i<consumerDataList.size();i++){
                    if(TextUtils.equals(consumerDataList.get(i).getIs_major_addr(),"Y")){
                        mTvNameAndTel.setText(consumerDataList.get(i).getConsignee() + "  " + consumerDataList.get(i).getMobile());
                        String area = AddressUtil.getSSQ(this,consumerDataList.get(i).getArea_id());
                        String address = consumerDataList.get(i).getAddress();
                        mTvAddress.setText(area + address);
                        mDeliveryAddress = area+address;
                        mContactPerson = consumerDataList.get(i).getConsignee();
                        mContactTel = consumerDataList.get(i).getMobile();
                    }
                }
            } else {
                mTvNameAndTel.setText("");
                mTvAddress.setText("编辑地址+");
            }
        }
    }
    @Override
    public void call(View v) {
        super.call(v);
        switch (v.getId()) {

            case R.id.btn_pay:
                if(mFromPage.equals(Constants.TYPE_GOLD_BUY)&&(TextUtils.isEmpty(mTvAddress.getText().toString())||"编辑地址+".equals(mTvAddress.getText().toString()))){
                    TipUtils.showToast(App.getInstance(),"请输入收货地址");
                    return;
                }

                if (mPayWay == 0&&!mFromPage.equals(Constants.TYPE_GOLD_BUY)) {
                    UserToken userToken = InfoProvider.getUserToken(App.getInstance());
                    if (userToken.getSmall_direct_flag().equals("N") && userToken.getPayment_password_flag().equals("Y")) {
                        showPasswordDialog();
                    } else if (userToken.getSmall_direct_flag().equals("Y") && Float.parseFloat(mTvPayMoney.getText().toString().replace("¥", "")) > Constants.SMALL_AMOUNT && userToken.getPayment_password_flag().equals("Y")) {
                        showPasswordDialog();
                    } else {
                        presenter.orderPay(mFromPage, mPayWay,mNum,mItemId,mEtFeedBack.getText().toString(), mTvPayMoney.getText().toString(),mDeliveryAddress ,mContactPerson, mContactTel,mOneType);
                    }
                }
                if(mPayWay==0){
                    if(!StringUtils.moneyComp(mWalletMoney, mTvPayMoney.getText().toString().replace("¥",""))){
                        TipUtils.showToast(App.getInstance(),"可用零钱余额不足",2);
                        return;
                    }
                }else{
                    presenter.orderPay(mFromPage, mPayWay,mNum,mItemId,mEtFeedBack.getText().toString(), mTvPayMoney.getText().toString(),mDeliveryAddress ,mContactPerson, mContactTel,mOneType);

                }
                break;

            case R.id.rl_address:  //地址选择

                Intent intent = new Intent(this, ReceivingAddressActivity.class);
                startActivity(intent);

                break;

        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {

        switch (checkedId) {
            case R.id.rb_wallet:    //零钱
                mPayWay = 0;
                break;
            case R.id.rb_alipay:   //支付宝
                mPayWay = 1;
                break;
            case R.id.rb_wechat:  //微信
                mPayWay = 2;
                break;
        }
    }


    @Override
    public void getUsableCashSuccess(UsableCash data) {
        mWalletMoney = data.getUsable_cash_balance();
        if (!TextUtils.isEmpty(mWalletMoney)) {
            mTvWallet.setText(mWalletMoney + "元");
        }
    }
    private void pushPayResult() {
        Disposable disposable =   RxBus.get().toFlowable(PayResultBean.class).subscribe(new Consumer<PayResultBean>() {
            @Override
            public void accept(PayResultBean payResultBean) throws Exception {
                if (payResultBean != null) {
                    if (payResultBean.result == Constants.PAY_RESULT_SUCCESS) {
                        TipUtils.showToast(App.getInstance(), getString(R.string.wallet_change_recharge_success));
                        //跳到订单页面
                        if(mFromPage.equals(Constants.TYPE_GOLD_BUY)) {
                            Intent intent = new Intent(OrderPayActivity.this, OrderActivity.class);
                            intent.putExtra("order_type", 4);
                            startActivity(intent);
                        }
                        finish();
                    } else if (payResultBean.result == Constants.PAY_RESULT_FAIL) {
                        TipUtils.showToast(App.getInstance(), getString(R.string.wallet_change_recharge_fail));
                    }
                }
            }
        });
        mCompositeDisposable.add(disposable);
    }
    @Override
    public void onFail(int code, String msg) {
        TipUtils.showToast(App.getInstance(),msg,2);
    }

    /**
     * 零钱支付成功
     */
    @Override
    public void walletPaySuccess() {
        TipUtils.showToast(App.getInstance(), getString(R.string.wallet_change_recharge_success));
        //跳到订单页面
        if(mFromPage.equals(Constants.TYPE_GOLD_BUY)) {
            Intent intent = new Intent(OrderPayActivity.this, OrderActivity.class);
            intent.putExtra("order_type", 4);
            startActivity(intent);
        }
        RxBus.get().post(new PayResultBean(Constants.PAY_RESULT_SUCCESS));
        finish();
    }

    @Override
    protected void onRefreshData() {

    }

    @Override
    public void showError(String msg) {

    }

    /**
     * 显示
     */
    private void showPasswordDialog() {
        mPasswordDialog = new PasswordDialog(this, R.layout.dialog_payment_pwd);
        mPasswordDialog.setOnDialogPsdCompareListener(this);
        mPasswordDialog.show();
        mPasswordDialog.setPsdDescription("零钱支付");
        mPasswordDialog.setPsdContent(mTvPayMoney.getText().toString().replace("¥", ""));
    }

    /**
     * 成功验证密码
     * @param dialog
     */
    @Override
    public void onPasswordCorrect(PasswordDialog dialog) {
        mPasswordDialog.dismiss();
        presenter.orderPay(mFromPage, mPayWay,mNum,mItemId,mEtFeedBack.getText().toString(), mTvPayMoney.getText().toString(),mDeliveryAddress ,mContactPerson, mContactTel,mOneType);
    }

    @Override
    public void onPasswordError(PasswordDialog dialog, String msg) {
        TipUtils.showToast(App.getInstance(), getString(R.string.wallet_payment_setting_password_wrong));
        mPasswordDialog.clearInput();
    }
}
